<template>
  <div class="address-edit-page">
    <van-nav-bar 
      :title="isEdit ? '编辑地址' : '新增地址'" 
      left-text="返回" 
      left-arrow 
      @click-left="handleBack"
    />

    <van-form @submit="saveAddress" ref="addressForm">
      <van-cell-group inset>
        <!-- 收货人 -->
        <van-field
          v-model="form.name"
          label="收货人"
          placeholder="请输入收货人姓名"
          :rules="[{ required: true, message: '请填写收货人姓名' }]"
        />

        <!-- 手机号码 -->
        <van-field
          v-model="form.tel"
          type="tel"
          label="手机号码"
          placeholder="请输入手机号码"
          :rules="[
            { required: true, message: '请填写手机号码' },
            { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确' }
          ]"
        />

        <!-- 省份输入 -->
        <van-field
          v-model="form.province"
          label="省份"
          placeholder="请输入省份（如：广东省）"
          :rules="[{ required: true, message: '请填写省份' }]"
        />

        <!-- 城市输入 -->
        <van-field
          v-model="form.city"
          label="城市"
          placeholder="请输入城市（如：深圳市）"
          :rules="[{ required: true, message: '请填写城市' }]"
        />

        <!-- 区县输入 -->
        <van-field
          v-model="form.county"
          label="区县"
          placeholder="请输入区县（如：南山区）"
          :rules="[{ required: true, message: '请填写区县' }]"
        />

        <!-- 详细地址 -->
        <van-field
          v-model="form.addressDetail"
          label="详细地址"
          placeholder="街道门牌、楼层等信息"
          :rules="[{ required: true, message: '请填写详细地址' }]"
        />

        <!-- 默认地址开关 -->
        <van-field name="isDefault" label="设为默认地址">
          <template #input>
            <van-switch v-model="form.isDefault" size="20" />
          </template>
        </van-field>
      </van-cell-group>

      <div style="margin: 16px;">
        <van-button 
          round 
          block 
          type="primary" 
          native-type="submit" 
          :loading="loading"
        >
          {{ loading ? '保存中...' : '保存地址' }}
        </van-button>
      </div>

      <!-- 编辑模式下显示删除按钮 -->
      <div v-if="isEdit" style="margin: 0 16px 20px;">
        <van-button 
          round 
          block 
          type="danger" 
          plain
          @click="showDeleteConfirm"
          :loading="deleting"
        >
          删除地址
        </van-button>
      </div>
    </van-form>

    <!-- 删除确认弹窗 -->
    <van-dialog
      v-model:show="showDeleteDialog"
      title="确认删除"
      show-cancel-button
      @confirm="confirmDelete"
    >
      <div style="padding: 20px; text-align: center;">
        确定要删除这个地址吗？删除后不可恢复
      </div>
    </van-dialog>
  </div>
</template>

<script setup>
import { reactive, ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { showToast, showConfirmDialog } from 'vant'
import { useAddressStore } from '@/stores/address'

const route = useRoute()
const router = useRouter()
const addressStore = useAddressStore()
const addressForm = ref(null)

// 状态管理
const loading = ref(false)
const deleting = ref(false)
const showDeleteDialog = ref(false)

// 表单数据
const form = reactive({
  id: '',
  name: '',
  tel: '',
  province: '',
  city: '',
  county: '',
  addressDetail: '',
  isDefault: false
})

// 计算属性
const isEdit = computed(() => !!route.query.id)

// 保存地址
const saveAddress = async () => {
  try {
    loading.value = true
    
    // 表单验证
    try {
      await addressForm.value.validate()
    } catch (error) {
      return showToast('请填写完整信息')
    }

    // 保存到Pinia Store
    const savedId = addressStore.saveAddress(form)
    
    showToast(isEdit.value ? '修改成功' : '添加成功')
    router.back()
  } catch (error) {
    console.error('保存失败:', error)
    showToast('保存失败')
  } finally {
    loading.value = false
  }
}

// 删除地址
const showDeleteConfirm = () => {
  showDeleteDialog.value = true
}

const confirmDelete = async () => {
  try {
    deleting.value = true
    addressStore.deleteAddress(form.id)
    showToast('删除成功')
    router.back()
  } catch (error) {
    console.error('删除失败:', error)
    showToast('删除失败')
  } finally {
    deleting.value = false
  }
}

// 返回处理（有修改时提示）
const handleBack = () => {
  const hasChanges = form.name || form.tel || form.province || form.addressDetail
  if (!hasChanges) {
    router.back()
    return
  }

  showConfirmDialog({
    title: '提示',
    message: '确定放弃编辑吗？您修改的内容将不会保存',
  }).then(() => {
    router.back()
  }).catch(() => {
    // 取消则不操作
  })
}

// 初始化编辑数据
onMounted(() => {
  if (isEdit.value) {
    // 优先从选中地址获取
    if (addressStore.selectedAddress?.id === route.query.id) {
      Object.assign(form, addressStore.selectedAddress)
    } 
    // 从地址列表获取
    else {
      const editAddress = addressStore.getAddressById(route.query.id)
      if (editAddress) {
        Object.assign(form, editAddress)
      } else {
        showToast('地址不存在')
        router.back()
      }
    }
  } else {
    form.id = Date.now().toString()
  }
})
</script>

<style scoped>
.address-edit-page {
  background-color: #f7f7f7;
  min-height: 100vh;
  padding-bottom: 20px;
  min-width: 78vh
}

.van-cell-group--inset {
  margin: 12px 0;
}

.delete-btn {
  margin-top: 12px;
}
</style>